<template>
  <div>
    <el-select
      v-model="currentValue"
      :disabled="disabled"
      :multiple-limit="multipleLimit"
      multiple
      clearable
      filterable
      remote
      default-first-option
      placeholder="请选择标签"
      :remote-method="remoteMethod"
      :loading="loading"
      @change="change"
    >
      <el-option v-for="item in optionList" :key="item" :label="item" :value="item"></el-option>
    </el-select>
  </div>
</template>

<script>
import { getSuggestTags } from "@/api/tag";

export default {
  name: "TagSelector",
  props: {
    moduleTypeId: {
      type: String,
      required: true
    },
    disabled: {
      type: Boolean,
      default: false
    },
    multipleLimit: {
      type: Number,
      default: 6 // tag默认最多6个，0代表不限制
    },
    value: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      currentValue: this.value,
      items: [],
      optionList: [],
      loading: false
    };
  },
  computed: {
    // isMultiple: {
    //   get() {
    //     return this.mode === "multiple";
    //   }
    // }
  },
  watch: {
    value(newValue) {
      this.currentValue = newValue;
    }
  },
  mounted() {
    this.load();
  },
  methods: {
    change(val) {
      this.$emit("input", val);
    },
    load() {
      this.getList(this.moduleTypeId);
    },
    remoteMethod(query) {
      if (query) {
        this.optionList = [query.trim()];
        // this.loading = true;
        const q = {
          keyWords: query.trim(),
          moduleTypeId: this.moduleTypeId,
          topNumber: 6,
          isFeatured: undefined
        };
        getSuggestTags(q).then(result => {
          result.forEach(tag => {
            if (!this.optionList.includes(tag.name)) {
              this.optionList.push(tag.name);
            }
          });
          // this.loading = false;
        });
      } else {
        this.optionList = [];
      }
    },
    getList(moduleTypeId) {
      this.loading = true;
      const q = {
        keyWords: undefined,
        moduleTypeId: moduleTypeId,
        topNumber: 6,
        isFeatured: undefined
      };
      getSuggestTags(q).then(result => {
        result.forEach(tag => {
          if (!this.optionList.includes(tag.name)) {
            this.optionList.push(tag.name);
          }
        });
        this.loading = false;
      });
    }
  }
};
</script>
